import { Empty, Popover, Spin, Tree } from 'antd';
import { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { AcceptanceManageAPI } from '../common/type';
import { AcceptanceManageContext, IAcceptanceActionEnum } from '../mconfig';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
import MyIcon from '@/components/MyIcon';
import pageStyles from '@/common/pageLayout.less';
import { ManageTreeTypeTitle } from './ManageTreeTypeTitle';
import { findObjectById } from '@/utils/findObjectById';

export const ManageTreeTypeView: React.FC<AcceptanceManageAPI.IManageTreeTypeView> = ({ typeTreeLoading, typeTreeData }) => {
  /**
   * 获取上下文
   */
  const { prefixCls, leftSelectKeys, leftExpandedKeys, leftAutoExpandParent, acceptanceDispatch } = useContext(AcceptanceManageContext);

  /**
   * 左侧树搜索数据
   */
  const [searchValueTree, setSearchValueTree] = useState<string>('');

  /**
   * 显示新增编辑按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseEnter = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'block';
    }
  };

  /**
   * 隐藏新增编辑按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseLeave = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'none';
    }
  };

  /**
   * 是否显示 详情气泡
   */
  const [showPopoverID, setShowPopoverID] = useState<string>('');

  /**
   * 显示 隐藏 详情方法
   * @param openID  显示图标
   * @param closeID  闭合图标
   * @param showPopo  显示详情的 id
   * @param isOpen  true 显示     false 隐藏
   */
  const clickEyeDetail = (openID: string, closeID: string, showPopo: string, isOpen: boolean) => {
    const eleOpen = document.getElementById(openID);
    const eleClose = document.getElementById(closeID);
    if (eleOpen) {
      eleOpen.style.display = isOpen ? 'none' : 'inline-block';
    }
    if (eleClose) {
      eleClose.style.display = isOpen ? 'inline-block' : 'none';
    }
    setShowPopoverID(showPopo);
  };

  // 对树结构数据处理
  const loopTreeData = (data: Record<string, any>[]): Record<string, any>[] => {
    return data?.map((item) => {
      const idName = item?.id + 'ShowBtnConditionTreeType';
      const flag = false;
      const detailEyeShow = item?.id + 'eyeShow' + Math.random();
      const detailEyeHiddren = item?.id + 'eyeHiddren' + Math.random();
      const showpopoverDom = item?.id + 'showpopoverDom';

      const content = (
        <div style={{ color: '#000000D9' }}>
          <p>
            状态：
            {item.storeState === 1 && <span style={{ color: 'green' }}>开启</span>}
            {item.storeState === 2 && <span style={{ color: 'green' }}>关闭</span>}
          </p>
        </div>
      );

      const text = item?.storeName;
      const nameLength = text?.length;
      const select = text?.search(searchValueTree);
      const searchLength = searchValueTree?.length;
      const afterStr = text?.slice(0, select);
      const selectStr = searchValueTree;
      const beforeStr = text?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.storeName}</span>
        );

      return {
        ...item,
        title: (
          <Popover
            placement="bottomLeft"
            content={content}
            // trigger={'click'}
            title={item?.storeName}
            color={'rgb(222 222 222)'}
            overlayClassName={'user-popover'}
            destroyTooltipOnHide={{ keepParent: false }}
            open={showpopoverDom == showPopoverID ? true : false}
          >
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
              }}
              id={item?.id + 'ConditionLeftTreeType'}
              onMouseEnter={() => {
                onTreeNodeMouseEnter(idName, flag);
              }}
              onMouseLeave={() => {
                onTreeNodeMouseLeave(idName, flag);
                clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
              }}
            >
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  width: '80%',
                }}
              >
                {titleTree}
              </div>
              <div
                id={idName}
                style={{
                  display: flag ? 'block' : 'none',
                  whiteSpace: 'nowrap',
                }}
              >
                <a
                  style={{
                    display: 'inline-block',
                  }}
                  id={detailEyeShow}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, showpopoverDom, true);
                  }}
                >
                  <EyeOutlined />
                </a>
                <a
                  id={detailEyeHiddren}
                  style={{
                    display: 'none',
                  }}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
                  }}
                >
                  <EyeInvisibleOutlined />
                </a>
              </div>
            </div>
          </Popover>
        ),
        key: item?.id,
        children: item?.childs && item?.childs?.length > 0 ? loopTreeData(item?.childs) : null,
      };
    });
  };

  /**
   * 渲染的树结构数据
   */
  const categoryTreeData = useMemo(() => {
    return loopTreeData(typeTreeData);
  }, [typeTreeData, searchValueTree, leftSelectKeys, showPopoverID]);

  /**
   * 保存选中的值
   * @param checkedKeys
   * @param treeNodes
   */
  const onTreeSelect = (checkedKeys: any, treeNodes: any) => {
    if (checkedKeys && checkedKeys?.length > 0) {
      const selectObj = findObjectById(checkedKeys[0], categoryTreeData, 'id');
      // 存到仓库中选中的仓库名称
      if (Object.keys(selectObj).length !== 0) {
        acceptanceDispatch({
          type: IAcceptanceActionEnum.LEFTSELECT_ROWNAME,
          payload: [selectObj.storeName],
        });
      }
      acceptanceDispatch({
        type: IAcceptanceActionEnum.LEFTSELECT_KEYS,
        payload: checkedKeys,
      });
      acceptanceDispatch({
        type: IAcceptanceActionEnum.TREETYPE_SELECTROW,
        payload: treeNodes?.node,
      });
    }
  };

  /**
   * 点击展开关闭树
   */
  const onTreeExpand = useCallback(
    (e, a) => {
      acceptanceDispatch({
        type: IAcceptanceActionEnum.LEFTEXPANDED_KEYS,
        payload: e,
      });
      acceptanceDispatch({
        type: IAcceptanceActionEnum.LEFTAUTO_PARENT,
        payload: false,
      });
    },
    [leftSelectKeys],
  );

  useEffect(() => {
    if (!(leftSelectKeys && leftSelectKeys?.length > 0) && typeTreeData && typeTreeData?.length > 0) {
      acceptanceDispatch({
        type: IAcceptanceActionEnum.LEFTSELECT_KEYS,
        payload: [typeTreeData?.[0]?.id],
      });
      acceptanceDispatch({
        type: IAcceptanceActionEnum.LEFTSELECT_ROWNAME,
        payload: [typeTreeData?.[0]?.storeName],
      });
      acceptanceDispatch({
        type: IAcceptanceActionEnum.TREETYPE_SELECTROW,
        payload: typeTreeData?.[0],
      });
    }
  }, [leftSelectKeys, typeTreeData]);

  return (
    <>
      <div className={prefixCls + 'flowCategoryStyle'}>
        <ManageTreeTypeTitle
          searchValueTree={searchValueTree}
          typeTreeData={categoryTreeData}
          saveSetSearchValue={(searchValue: string) => {
            setSearchValueTree(searchValue);
          }}
        />
        <div className={prefixCls + 'flowCategoryStyle-bodyContent'}>
          <Spin spinning={typeTreeLoading}>
            <ScrollBarLayout
              style={{
                padding: '0px 0px 5px',
              }}
            >
              {categoryTreeData && categoryTreeData?.length > 0 ? (
                <Tree
                  treeData={categoryTreeData}
                  blockNode={true}
                  selectedKeys={leftSelectKeys}
                  onSelect={onTreeSelect}
                  expandedKeys={leftExpandedKeys}
                  onExpand={onTreeExpand}
                  autoExpandParent={leftAutoExpandParent}
                />
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </ScrollBarLayout>
          </Spin>
        </div>
      </div>
    </>
  );
};
